package com.derbysoft.ota.application.util;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

import javax.xml.bind.JAXBElement;

import org.apache.commons.lang.StringUtils;

import com.derbysoft.ota.interfaces.protocol._2009a.FormattedTextTextType;
import com.derbysoft.ota.interfaces.protocol._2009a.ObjectFactory;
import com.derbysoft.ota.interfaces.protocol._2009a.ParagraphType;

public abstract class ParagraphTypes {

	public static ParagraphType of(String value) {
		return of(value, ParagraphType.class);
	}
	
	public static <T extends ParagraphType> T of(String value, Class<T> clazz) {
		if (StringUtils.isBlank(value)) {
			return null;
		}
	    T paragraphType = Instances.create(clazz);
	    FormattedTextTextType text = new FormattedTextTextType();
	    text.setValue(value);
		paragraphType.getTextOrImageOrURL().add(new ObjectFactory().createParagraphTypeText(text));
	    return paragraphType;
	}

	public static String toString(List<JAXBElement<? extends Serializable>> textOrImageOrURL) {
		StringBuilder builder = new StringBuilder();
		
		for (Iterator<JAXBElement<? extends Serializable>> iter = textOrImageOrURL.iterator(); iter.hasNext();) {
			builder.append(eachElement(iter.next()));
			if (iter.hasNext()) {
				builder.append("; ");
			}
		}
		
		return builder.toString();
	}

	private static String eachElement(JAXBElement<? extends Serializable> jaxbElement) {
		Object value = jaxbElement.getValue();
		if (FormattedTextTextType.class.isInstance(value)) {
			return ((FormattedTextTextType) value).getValue();
		}
		throw new IllegalArgumentException("Unsupported TextOrImageOrURL type : " + value.getClass());
	}

}
